package address

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"regexp"
	"shop/formdata"
	"shop/internal/controller/base"
	add3 "shop/internal/server/address"
)

func AddressCreate(c *gin.Context) {
	userID := c.MustGet("user_id").(int) // 获取用户ID
	var add formdata.Address
	if err := c.ShouldBindJSON(&add); err != nil {
		base.RespData(c, nil, err)
		return
	}
	if add.Table == "" {
		base.RespData(c, nil, fmt.Errorf("Table不能为空"))
		return
	}
	if add.Recipient == "" {
		base.RespData(c, nil, fmt.Errorf("Recipient不能为空"))
		return
	}
	// 修正正则匹配逻辑
	matched, _ := regexp.MatchString(`^1[3-9]\d{9}$`, add.Phone)
	if !matched {
		base.RespData(c, nil, fmt.Errorf("手机号格式错误"))
		return
	}
	if add.AddressLine == "" {
		base.RespData(c, nil, fmt.Errorf("AddressLine不能为空"))
		return
	}
	if add.City == "" {
		base.RespData(c, nil, fmt.Errorf("City不能为空"))
		return
	}
	if add.Province == "" {
		base.RespData(c, nil, fmt.Errorf("Province不能为空"))
		return
	}
	if add.Village == "" {
		base.RespData(c, nil, fmt.Errorf("Village不能为空"))
		return
	}
	if add.UnDefault != 1 && add.UnDefault != 0 {
		base.RespData(c, nil, fmt.Errorf("UnDefault不能为空"))
		return
	}
	addressAdd, err := add3.AddressAdd(add)
	if err != nil {
		base.RespData(c, nil, err)
		return
	}
	message := addressAdd.Province + "/" + addressAdd.City + "/" + "/" + addressAdd.Village

	base.RespData(c, map[string]interface{}{
		"userId":      userID,
		"name":        addressAdd.Recipient,
		"phone":       addressAdd.Phone,
		"address":     message,
		"addressLine": addressAdd.AddressLine,
		"label":       addressAdd.Table,
		"unDefault":   addressAdd.UnDefault,
	}, nil)
}

func AddressList(c *gin.Context) {
	addressList, err := add3.AddressList()
	if err != nil {
		return
	}

	base.RespData(c, addressList, nil)
}
